package com.songlanyun.modules.advertisement.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.songlanyun.common.utils.HouniaoApiUtil;
import com.songlanyun.common.utils.R;
import com.songlanyun.modules.account.entity.AccountEntity;
import com.songlanyun.modules.account.service.AccountService;
import com.songlanyun.modules.advconfig.dao.AdvConfigDao;
import com.songlanyun.modules.advconfig.dao.AdvertisingViewingRecordsDao;
import com.songlanyun.modules.advconfig.entity.AdvConfig;
import com.songlanyun.modules.advconfig.entity.AdvertisingViewingRecords;
import com.songlanyun.modules.notice.service.GoodsNoticeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;

@Slf4j
@RestController
@RequestMapping("api/advertisement")
public class AdvertisementController {

    @Autowired
    private GoodsNoticeService goodsNoticeService;

    @Autowired
    private HouniaoApiUtil houniaoApiUtil;

    @Autowired
    private AccountService accountService;

    @Autowired
    private AdvConfigDao advConfigDao;

    @Autowired
    private AdvertisingViewingRecordsDao advertisingViewingRecordsDao;

    /**
     * 看完广告
     */
    @PostMapping()
    public R seeAdvertisementSuccess(@RequestParam Long userId){

        AdvConfig advConfig = advConfigDao.selectOne(new LambdaQueryWrapper<AdvConfig>().orderByDesc(AdvConfig::getId).last("LIMIT 1"));
        AccountEntity user = accountService.getUserById(userId,true);

        user.setSeeTimes(user.getSeeTimes()+1);
        //看满后做记录
        if (user.getSeeTimes() == advConfig.getSeeTimesOneDay()){
            AdvertisingViewingRecords advertisingViewingRecords = new AdvertisingViewingRecords();
            advertisingViewingRecords.setCreateTime(new Date());
            advertisingViewingRecords.setUserId(userId);
            advertisingViewingRecordsDao.insert(advertisingViewingRecords);
        }
        boolean b = accountService.updateById(user);

        
        if (b){
            return R.ok();
        }else {
            return R.error();            
        }
    }

    //查询用户观看次数
    @GetMapping("/times")
    public R getUserTimes(@RequestParam Long userId){
        AccountEntity user = accountService.getUserById(userId,true);
        AdvConfig advConfig = advConfigDao.selectOne(new LambdaQueryWrapper<AdvConfig>().orderByDesc(AdvConfig::getId).last("LIMIT 1"));
        HashMap<String,Object> map = new HashMap<>();
        int residueSeeTimes = advConfig.getSeeTimesOneDay() - user.getSeeTimes();
        map.put("residueSeeTimes",residueSeeTimes);
        map.put("seeTimes",user.getSeeTimes());
        return R.ok().put("data",map);
    }


}
